package com.th.apicenter.rta.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.taobao.api.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RopHttp {

    public  static final String APP_KEY="35029256";
    public static final String APP_SECRET="8cf5f6606b5d615efdbe2f8c04343873";
    //公共参数集合
    public static final Map<String, String> params;

    static {
        //公共参数
        params = new HashMap<>();
        params.put("app_key",APP_KEY);
        params.put("sign_method", "md5");
        params.put("format", "json");
        params.put("v", "2.0");
        params.put("simplify", "true");
    }

    //http://gw.api.taobao.com/router/rest?
    // app_key=35029256&method=taobao.tbk.rta.consumer.match&v=2.0&sign=F9F4CF2430030566316C0CFAB75A9153&timestamp=2025-07-18+11%3A07%3A31&partner_id=top-apitools&format=json&sign_method=md5&device_value=d323cac31730150a8ff491b26ecc0baf&adzone_id=116087600242&device_type=IMEI&strategy_id_list=20150318020023485

    /**
     * 设置参数工具方法
     *
     * @param key
     * @param value
     */
    public static void setParameter(Map<String, Object> param, String key, String value) {
        if (!StringUtils.isEmpty(value)) {
            param.put(key, value);
        }
    }

    /**
     * 获取快麦数据
     */
    /*public static JSONObject postResult(Map<String, String> param) {
        String timestamp = DateTool.nowDate();
        //时间戳
        param.put("timestamp", timestamp);
        try {
            //签名加密
            String sign = RopUtils.serverSign(param, RopUtils.AppSecret, "md5");
            param.put("sign", sign);
        } catch (Exception e) {
            e.printStackTrace();                     //输出异常性质
        }

        //获取数据
        String result = HttpUtil.post(RopUtils.KmUrl, JSON.toJSONString(param),5000);
        //转JSON格式
        JSONObject resultJSON = JSON.parseObject(result);
        boolean success = resultJSON.getBoolean("success");
        if (!success) {
            log.error(String.format("快麦%s接口返回：%s",param.get("method"),result));
            throw new CustomRunException(resultJSON.getString("msg"));
        }
        return resultJSON;

    }*/


    public static String signTopRequest(Map<String, Object> params, String signMethod) throws IOException {
        //时间戳
        params.put("timestamp", nowDate());
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (Constants.SIGN_METHOD_MD5.equals(signMethod)) { //签名的摘要算法，可选值为：hmac，md5，hmac-sha256
            query.append(APP_SECRET);
        }
        for (String key : keys) {
            String value = params.get(key).toString();
            query.append(key).append(value);
        }

        // 第三步：使用MD5/HMAC加密
        byte[] bytes;
        if (Constants.SIGN_METHOD_HMAC.equals(signMethod)) {
            bytes = encryptHMAC(query.toString(), APP_SECRET);
        } else {
            query.append(APP_SECRET);
            bytes = encryptMD5(query.toString());
        }

        // 第四步：把二进制转化为大写的十六进制(正确签名应该为32大写字符串，此方法需要时使用)
        return byte2hex(bytes);
    }

    public static byte[] encryptHMAC(String data, String secret) throws IOException {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static byte[] encryptMD5(String data) throws IOException {

        return encryptMD5(data.getBytes(StandardCharsets.UTF_8));
    }

    public static byte[] encryptMD5(byte[] data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data);
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
    public static String nowDate() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(calendar.getTime());
    }

}
